package com.slipper.system.restore.controller;

import com.slipper.core.cache.CacheUtil;
import com.slipper.system.backup.bo.BackupBO;
import com.slipper.system.backup.service.BackupRestoreService;
import com.slipper.system.restore.bo.RestoreBO;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.slipper.system.restore.service.RestoreService;
import com.slipper.util.ResultUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * 数据恢复信息表
 */
@RestController
@RequestMapping("/system/restore")
public class RestoreController {
    @Resource
    private RestoreService restoreService;
    @Resource
    private BackupRestoreService backupRestoreService;
    
    @PostMapping(value = "/queryLast")
    public String queryLast() {
        return ResultUtil.successResult(restoreService.queryLast());
    }

    @PostMapping(value = "/restore")
    public String restore(RestoreBO bo) throws Exception {
        if (bo.getFile() == null) {
            return ResultUtil.failureResult("请选择文件！");
        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(bo.getFile().getInputStream()));
        BackupBO backup = backupRestoreService.restore(reader);
        RestoreBO restore = new RestoreBO();
        restore.setName(backup.getName());
        restore.setType(backup.getType());
        restore.setMode(backup.getMode());
        restoreService.save(restore);

        CacheUtil.clearAll();
        return ResultUtil.successResult("恢复备份数据【" + backup.getName() + "】成功！");
    }
}
